package com.huika.dealontop.control.nearby.fragment;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HeaderViewListAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.homepage.Interface.StopRefreshInterface;
import com.huika.dealontop.control.homepage.activity.SearchActivity;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.nearby.adapter.NearbyAllLocalAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyBusinessAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyFilterAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyFoodListAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyFoodRightAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyGrouponAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyLocalListAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbyLocalRightAdapter;
import com.huika.dealontop.control.nearby.adapter.NearbySortAdapter;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.support.domain.FilterBean;
import com.huika.dealontop.support.domain.NearbyBusinessBean;
import com.huika.dealontop.support.domain.NearbyGrouponBean;
import com.huika.dealontop.support.domain.NearbyItemValuesBean;
import com.huika.dealontop.support.domain.NearbyListBean;
import com.huika.dealontop.support.domain.NearbyLocalItemBean;
import com.huika.dealontop.support.domain.NearbyLocalItemChildBean;
import com.huika.dealontop.support.domain.NearbyLocalListBean;
import com.huika.dealontop.support.domain.SearchResultBean;
import com.huika.dealontop.support.domain.SortBean;
import com.huika.dealontop.support.event.SelectNearByEvent;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.ScreenUtil;
import com.huika.dealontop.utils.UIUtils;
import com.huika.huikalib.utils.NetUtil;
import com.huika.huikalib.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class NearbyFragment extends BaseFra implements BaseFra.OnInitShowListener, GMapUtil.MyLocationListener,
        StopRefreshInterface {
    private RadioGroup rg_title;
    private RadioButton rb_title_left, rb_title_right;
    private LinearLayout ll_nearby_list_shaixuan, ll_nearby_list_nearby, ll_nearby_list_meishi, ll_nearby_list_paixu,
            ll_nearby_list_more, ll_nearby_list_all, ll_nearby_list_shaixuans;
    private Button btn_nearby_list_shaixuan, btn_nearby_list_nearby, btn_nearby_list_meishi, btn_nearby_list_paixu;
    private ImageView iv1, iv2, iv3, iv4, back_to_top;
    private TextView tv_left;
    private ImageView iv_search;
    private ImageButton ib_nearby_list_more;
    private HorizontalScrollView hs_nearby_list_more;
    private ViewStub vs_seleteArea;
    private View v_seleteArea;
    private View iv_seleteArea;
    private TextView homepage_tv_refresh_position;
    private ImageView homepage_iv_refresh;
    private ListView lv_seleteArea_left, lv_seleteArea_right;
    private NearbyLocalListAdapter LocalLeftListAdapter;
    private NearbyLocalRightAdapter nearbyLocalRightAdapter;
    private NearbyFoodListAdapter nearbyFoodListAdapter;
    private NearbyFoodRightAdapter nearbyFoodRightAdapter;
    private NearbyFilterAdapter nearbyFilterAdapter;
    private NearbySortAdapter nearbySortAdapter;
    private NearbyAllLocalAdapter nearbyAllAdapter;
    private NearbyBusinessAdapter nearbyBusinessAdapter;
    private NearbyGrouponAdapter nearbyGrouponAdapter;
    private List<SortBean> list = new ArrayList<SortBean>();
    private List<SortBean> Sortlist = new ArrayList<SortBean>();
    private List<FilterBean> filterlist = new ArrayList<FilterBean>();
    private List<NearbyLocalListBean> LocalList = new ArrayList<NearbyLocalListBean>();
    private List<NearbyLocalItemBean> LocalItemList = new ArrayList<NearbyLocalItemBean>();
    private List<NearbyLocalItemChildBean> LocalAlllist = new ArrayList<NearbyLocalItemChildBean>();
    private List<NearbyListBean> GoodsList = new ArrayList<NearbyListBean>();
    private List<NearbyItemValuesBean> GoodsItemList = new ArrayList<NearbyItemValuesBean>();
    private List<NearbyGrouponBean> NearbyGrouponList = new ArrayList<NearbyGrouponBean>();
    private List<NearbyBusinessBean> nearbyBusinessList = new ArrayList<NearbyBusinessBean>();
    private View view = null;
    private View layouts = null;
    private PopupWindow pop = null;
    private int mCurrenSortIndex, mCurrenFilterIndex, mCurrenLocalLeftIndex, mCurrenLocalAllIndex,
            mCurrenLocalRightIndex,
            mCurrenFoodLeftIndex, mCurrenFoodRightIndex;
    private PullToRefreshListView mPullRefreshListView;
    private JSONWrapAjaxParams ajaxParams;
    private FormResultRequest<List<NearbyGrouponBean>> request;
    private JSONWrapAjaxParams ajaxParams2;
    private FormResultRequest<List<NearbyBusinessBean>> request2;
    public static final String SORTNUM_ID = "sortnum_id";
    private int isForHomeDelivery;
    private int isForOrder;
    private int isForLimitRule;
    private int sort;
    private int sortnum;
    private int areaId;
    private int categoryId;
    private boolean checknet;
    private ArrayList<SearchResultBean> mSearchResultList = new ArrayList<SearchResultBean>();
    private int sortnumid;
    private GMapUtil gMapUtil;
    private int widthPixels;
    private float mStartY = 0, mLastY = 0, mLastDeltaY;
    private boolean check = false;
    private int totalSizeone, totalSizetwo;
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 0;// 标记上次滑动位置

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View root = inflater.inflate(R.layout.frag_nearby, container, false);
        return root;
    }

    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        rg_title = (RadioGroup) parentView.findViewById(R.id.title_gp);
        rb_title_left = (RadioButton) parentView.findViewById(R.id.title_left);
        rb_title_right = (RadioButton) parentView.findViewById(R.id.title_right);
        view = (View) parentView.findViewById(R.id.view);
        ll_nearby_list_shaixuans = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_shaixuans);
        ll_nearby_list_shaixuan = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_shaixuan);
        ll_nearby_list_nearby = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_nearby);
        ll_nearby_list_meishi = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_meishi);
        ll_nearby_list_paixu = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_paixu);
        ll_nearby_list_more = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_more);
        ll_nearby_list_all = (LinearLayout) parentView.findViewById(R.id.ll_nearby_list_all);
        btn_nearby_list_shaixuan = (Button) parentView.findViewById(R.id.btn_nearby_list_shaixuan);
        btn_nearby_list_nearby = (Button) parentView.findViewById(R.id.btn_nearby_list_nearby);
        btn_nearby_list_meishi = (Button) parentView.findViewById(R.id.btn_nearby_list_meishi);
        btn_nearby_list_paixu = (Button) parentView.findViewById(R.id.btn_nearby_list_paixu);
        back_to_top = (ImageView) parentView.findViewById(R.id.iv_back_to_top);
        iv1 = (ImageView) parentView.findViewById(R.id.iv1);
        iv2 = (ImageView) parentView.findViewById(R.id.iv2);
        iv3 = (ImageView) parentView.findViewById(R.id.iv3);
        iv4 = (ImageView) parentView.findViewById(R.id.iv4);
        ib_nearby_list_more = (ImageButton) parentView.findViewById(R.id.ib_nearby_list_more);
        hs_nearby_list_more = (HorizontalScrollView) parentView.findViewById(R.id.hs_nearby_list_more);
        tv_left = (TextView) parentView.findViewById(R.id.lefts);
        iv_search = (ImageView) parentView.findViewById(R.id.title_right_ivs);
        vs_seleteArea = (ViewStub) parentView.findViewById(R.id.vs_nearby_list);
        mPullRefreshListView = (PullToRefreshListView) parentView.findViewById(R.id.pull_refresh_list);
        homepage_tv_refresh_position = (TextView) parentView.findViewById(R.id.homepage_tv_refresh_position);
        homepage_iv_refresh = (ImageView) parentView.findViewById(R.id.homepage_iv_refresh);
        homepage_iv_refresh.setOnClickListener(this);
        // 查找筛选区域视图
        v_seleteArea = vs_seleteArea.inflate();
        v_seleteArea.setVisibility(View.INVISIBLE);
        gMapUtil = new GMapUtil(getActivity(), this);
        gMapUtil.getLatestGeoAddress();
        gMapUtil.setStopRefreshAnim(this);
        assignSeleteViews();
        InitonListener();
        InitAapter();
        InitSelectItemView();
        SelectContentItemView();
        EventBus.getDefault().register(this);
        startOverallLoading(mPullRefreshListView);
        executeGetNearbyGrouponPro();
        executeGetAreas();
        executeGetCategories();
        executeGetNearbyGrouponMer();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void setSelectedId(int id) {
        categoryId = id;
        int index = -1;
        for (int i = 0; i < GoodsList.size(); i++) {
            if (GoodsList.get(i).CategoryId == categoryId) {
                index = i;
                break;
            }
        }

        if (index > -1) {
            onFoodCategoryItemClick(index);
            onFoodChildItemOnClick(0);
        }
    }


    /**
     * 点击标题分类监听事件
     */
    private void InitSelectItemView() {
        // 点击标题左布局分类监听事件
        lv_seleteArea_left.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              /*  if (lv_seleteArea_left.getAdapter() instanceof NearbyLocalListAdapter) {
                    showLocalclick(position);
                }*/
                if (lv_seleteArea_left.getAdapter() instanceof NearbyAllLocalAdapter) {
                    showLocalAllClick(position);
                }
                if (lv_seleteArea_left.getAdapter() instanceof NearbyFoodListAdapter) {
                    onFoodCategoryItemClick(position);
                }
                if (lv_seleteArea_left.getAdapter() instanceof NearbySortAdapter) {
                    mCurrenSortIndex = position + 1;
                    //请求网络查询
                    showLoadingDialog("");
                    if (sort == 0) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).isSelete = false;
                        }
                        nearbySortAdapter.getItem(position).isSelete = true;
                        executeGetNearbyGrouponPro();
                    } else {
                        for (int i = 0; i < Sortlist.size(); i++) {
                            Sortlist.get(i).isSelete = false;
                        }
                        nearbySortAdapter.getItem(position).isSelete = true;
                        executeGetNearbyGrouponMer();
                    }
                    nearbySortAdapter.notifyDataSetChanged();
                    btn_nearby_list_paixu.setText(nearbySortAdapter.getItem(position).getSort_Name());
                    refreshSortButtonName();
                    if (sort == 0) {
                        PreferencesHelper.setString("pro_sortnum", nearbySortAdapter.getItem(position).getSort_Name());
                    } else {
                        PreferencesHelper.setString("mer_sortnum", nearbySortAdapter.getItem(position).getSort_Name());
                    }
                }

                if (lv_seleteArea_left.getAdapter() instanceof NearbyFilterAdapter ||
                        lv_seleteArea_left.getAdapter() instanceof HeaderViewListAdapter) {
                    mCurrenFilterIndex = position;
                    nearbyFilterAdapter.getItem(position).isSelete = !nearbyFilterAdapter.getItem(position).isSelete;
                    nearbyFilterAdapter.notifyDataSetChanged();
                }
            }
        });
        // 点击标题右布局分类监听事件
        lv_seleteArea_right
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        /*if (lv_seleteArea_right.getAdapter() instanceof NearbyLocalRightAdapter) {
                            showLocalRightClick(position);

                        }*/
                        if (lv_seleteArea_right.getAdapter() instanceof NearbyFoodRightAdapter) {
                            {
                                onFoodChildItemOnClick(position);

                            }
                        }
                    }
                });
    }

    private void showLocalRightClick(int position) {
        //重置上一次筛选条件 改变字体显示
        resetLocalSelect(false);

        nearbyLocalRightAdapter.getItem(position).isSelete = true;
        nearbyLocalRightAdapter.notifyDataSetChanged();
        LocalLeftListAdapter.getItem(mCurrenLocalLeftIndex).ischild = position;
        LocalLeftListAdapter.notifyDataSetChanged();
        //请求网络查询
        areaId = nearbyLocalRightAdapter.getItem(position).areaId;
        showLoadingDialog("");
        if (sort == 0) {
            executeGetNearbyGrouponPro();
        } else {
            executeGetNearbyGrouponMer();
        }
        if (sort == 0) {
            PreferencesHelper.setString("pro_local", nearbyLocalRightAdapter.getItem(position)
                    .text);
        } else {
            PreferencesHelper.setString("mer_local", nearbyLocalRightAdapter.getItem(position)
                    .text);
        }
        if (position == 0) {
            refreshLocalButtonName(LocalLeftListAdapter.getItem(mCurrenLocalLeftIndex).text);
        } else {
            refreshLocalButtonName(nearbyLocalRightAdapter.getItem(position).text);
        }
    }

    private void showLocalAllClick(int position) {
        //重置上一次筛选条件 改变字体显示
        mCurrenLocalAllIndex = position;
        //更新左边列表显示
        for (int i = 0; i < LocalAlllist.size(); i++) {
            LocalAlllist.get(i).isSelete = false;
        }
        nearbyAllAdapter.getItem(mCurrenLocalAllIndex).isSelete = true;
        nearbyAllAdapter.notifyDataSetChanged();
        //请求网络查询
        areaId = nearbyAllAdapter.getItem(position).areaId;
        showLoadingDialog("");
        if (sort == 0) {
            executeGetNearbyGrouponPro();
        } else {
            executeGetNearbyGrouponMer();
        }
        if (position == 0) {
            if (sort == 0) {
                PreferencesHelper.setString("pro_local", getString(R.string.nearby_fujin));
            } else {
                PreferencesHelper.setString("mer_local", getString(R.string.nearby_fujin));
            }
            refreshLocalButtonName(getString(R.string.nearby_fujin));
        } else {
            if (sort == 0) {
                PreferencesHelper.setString("pro_local", nearbyAllAdapter.getItem(position)
                        .text);
            } else {
                PreferencesHelper.setString("mer_local", nearbyAllAdapter.getItem(position)
                        .text);
            }
            refreshLocalButtonName(nearbyAllAdapter.getItem(position).text);
        }
    }

    private void resetLocalSelect(boolean resetSelete) {
        for (int i = 0; i < LocalList.size(); i++) {
            if (LocalList.get(i).ischild > -1) {
                LocalList.get(i).ischild = -1;
                if (resetSelete)
                    LocalList.get(i).isSelete = false;
                for (NearbyLocalItemBean bean : LocalList.get(i).nodes) {
                    bean.isSelete = false;
                }
            }
        }
    }

    private void showLocalclick(int position) {
        mCurrenLocalLeftIndex = position;
        //更新左边列表显示
        for (int i = 0; i < LocalList.size(); i++) {
            LocalList.get(i).isSelete = false;
        }
        LocalList.get(position).isSelete = true;
        List<NearbyLocalItemBean> nodes = LocalLeftListAdapter.getItem(position).nodes;
        nearbyLocalRightAdapter.setGroup(LocalLeftListAdapter.getItem(position).nodes);
        //如果没有二级数据 直接加载数据
        if (nodes == null || nodes.size() == 0) {
            //重置区域选择
            resetLocalSelect(false);
            LocalList.get(position).ischild = 0;
            areaId = LocalLeftListAdapter.getItem(position).areaId;
            LocalLeftListAdapter.notifyDataSetChanged();
            showLoadingDialog("");
            if (sort == 0) {
                executeGetNearbyGrouponPro();
            } else {
                executeGetNearbyGrouponMer();
            }
            for (NearbyLocalItemBean bean : nearbyLocalRightAdapter.getGroup()) {
                bean.isSelete = false;
            }
            if (sort == 0) {
                PreferencesHelper.setString("pro_local", getString(R.string.nearby_fujin));
            } else {
                PreferencesHelper.setString("mer_local", getString(R.string.nearby_fujin));
            }
            refreshLocalButtonName(getString(R.string.nearby_fujin));
        }
        LocalLeftListAdapter.notifyDataSetChanged();
    }


    private void onFoodCategoryItemClick(int position) {

        mCurrenFoodLeftIndex = position;
        //更新背景颜色
        for (int i = 0; i < GoodsList.size(); i++) {
            GoodsList.get(i).isSelete = false;
        }
        GoodsList.get(position).isSelete = true;

        //更新右边数据
        List<NearbyItemValuesBean> nodes = nearbyFoodListAdapter.getItem(position).nodes;
        nearbyFoodRightAdapter.setGroup(nearbyFoodListAdapter.getItem(position).nodes);

        //如果没有二级数据 直接加载数据
        if (nodes == null || nodes.size() == 0) {
            //重置上一次筛选条件 改变字体显示
            resetGoodsSelect(false);

            GoodsList.get(position).ischild = 0;
            categoryId = nearbyFoodListAdapter.getItem(position).CategoryId;
            showLoadingDialog("");
            if (sort == 0) {
                executeGetNearbyGrouponPro();
            } else {
                executeGetNearbyGrouponMer();
            }
            if (sort == 0) {
                PreferencesHelper.setString("pro_category", getString(R.string.nearby_meishi));
            } else {
                PreferencesHelper.setString("mer_category", getString(R.string.nearby_meishi));
            }
            refreshFoodButtonName(getString(R.string.nearby_meishi));
        }
        nearbyFoodListAdapter.notifyDataSetChanged();
    }

    private void releaseSelect() {

        //重置区域选择
        resetLocalSelect(true);

        //重置分类
        resetGoodsSelect(true);

        //重置筛选
        for (int i = 0; i < nearbyFilterAdapter.getCount(); i++) {
            nearbyFilterAdapter.getItem(i).isSelete = false;
        }

    }

    private void resetGoodsSelect(boolean resetGoodSelect) {
        for (int i = 0; i < GoodsList.size(); i++) {
            if (GoodsList.get(i).ischild > -1) {
                GoodsList.get(i).ischild = -1;
                if (resetGoodSelect)
                    GoodsList.get(i).isSelete = false;
                for (NearbyItemValuesBean bean : GoodsList.get(i).nodes) {
                    bean.isSelete = false;
                }
            }
        }
    }

    private void onFoodChildItemOnClick(int position) {
        //重置上一次筛选条件 改变字体显示
        for (int i = 0; i < GoodsList.size(); i++) {
            if (GoodsList.get(i).ischild > -1) {
                GoodsList.get(i).ischild = -1;
                for (NearbyItemValuesBean bean : GoodsList.get(i).nodes) {
                    bean.isSelete = false;
                }
            }
        }

        nearbyFoodRightAdapter.getItem(position).isSelete = true;
        nearbyFoodRightAdapter.notifyDataSetChanged();
        nearbyFoodListAdapter.getItem(mCurrenFoodLeftIndex).ischild = position;
        nearbyFoodListAdapter.notifyDataSetChanged();
        categoryId = nearbyFoodRightAdapter.getItem(position).CategoryId;
        //请求网络查询
        showLoadingDialog("");
        if (sort == 0) {
            executeGetNearbyGrouponPro();
        } else {
            executeGetNearbyGrouponMer();
        }
        if (sort == 0) {
            PreferencesHelper.setString("pro_category", nearbyFoodRightAdapter.getItem(position)
                    .CategoryName);
        } else {
            PreferencesHelper.setString("mer_category", nearbyFoodRightAdapter.getItem(position)
                    .CategoryName);
        }
        if (position == 0) {
            refreshFoodButtonName(nearbyFoodListAdapter.getItem(mCurrenFoodLeftIndex).CategoryName);
        } else {
            refreshFoodButtonName(nearbyFoodRightAdapter.getItem(position).CategoryName);
        }
    }

    //按下去时 位于父空件的位置
    float startY, mY, sY;

    /**
     * 点击列表条目的监听事件
     */
    private void SelectContentItemView() {
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                checknet = false;
                if (sort == 0) {
                    CURRENT_PAGE = 1;
                    executeGetNearbyGrouponPro();
                } else {
                    CURRENT_PAGES = 1;
                    executeGetNearbyGrouponMer();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                checknet = false;
                // 加载下一页
                if (sort == 0) {
                    CURRENT_PAGE++;
                    ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
                    executeRequest(request);
                } else {
                    CURRENT_PAGES++;
                    ajaxParams2.putCommonTypeParam("pageNo", CURRENT_PAGES);
                    executeRequest(request2);
                }
            }
        });
        mPullRefreshListView.getRefreshableView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final float y = event.getY();
                float translationY = ll_nearby_list_all.getTranslationY();

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startY = ll_nearby_list_all.getY();
                        mStartY = y;
                        mLastY = mStartY;
                        sY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mY = event.getY();
                        float dY = mY - sY;
                        float tY = dY + startY;
                        if (tY > 0 && tY < ll_nearby_list_all.getHeight()) {
                            ll_nearby_list_all.setY(tY);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        int pos = mPullRefreshListView.getRefreshableView().getFirstVisiblePosition();
                        float eY = ll_nearby_list_all.getY();
                        if (eY - startY < 0) { //向上移动
                            animUp();
                        } else if (eY - startY > 0 || pos == 0 || pos == 1) {
                            animDown();
                        } else {
                            //eY - startY == 0
                            break;
                        }
                        break;
                }
                return false;
            }
        });
        mPullRefreshListView.getRefreshableView().setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                        scrollFlag = false;
                        // 判断滚动到底部
                        if (mPullRefreshListView.getRefreshableView().getLastVisiblePosition() == (mPullRefreshListView
                                .getRefreshableView().getCount() - 1)) {
                            back_to_top.setVisibility(View.VISIBLE);
                        }
                        // 判断滚动到顶部
                        if (mPullRefreshListView.getRefreshableView().getFirstVisiblePosition() == 0 ||
                                mPullRefreshListView.getRefreshableView().getFirstVisiblePosition() == 1) {
                            back_to_top.setVisibility(View.GONE);
                        }

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                        scrollFlag = true;
                        // 判断滚动到底部
                        if (mPullRefreshListView.getRefreshableView().getLastVisiblePosition() == (mPullRefreshListView
                                .getRefreshableView().getCount() - 1)) {
                            back_to_top.setVisibility(View.VISIBLE);
                        }
                        // 判断滚动到顶部
                        if (mPullRefreshListView.getRefreshableView().getFirstVisiblePosition() == 0 ||
                                mPullRefreshListView.getRefreshableView().getFirstVisiblePosition() == 1) {
                            back_to_top.setVisibility(View.GONE);
                        }
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                        scrollFlag = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 当开始滑动且ListView底部的Y轴点超出屏幕最大范围时，显示或隐藏顶部按钮
                if (scrollFlag
                        && ScreenUtil.getScreenViewBottomHeight(mPullRefreshListView) >= ScreenUtil
                        .getScreenHeight(getActivity())) {
                    if (firstVisibleItem > lastVisibleItemPosition) {// 上滑
                        back_to_top.setVisibility(View.VISIBLE);
                    } else if (firstVisibleItem < lastVisibleItemPosition) {// 下滑
                        back_to_top.setVisibility(View.GONE);
                    } else {
                        return;
                    }
                    lastVisibleItemPosition = firstVisibleItem;
                }
            }
        });
        mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        nearbyGrouponAdapter = new NearbyGrouponAdapter(UIUtils.getContext());
        nearbyBusinessAdapter = new NearbyBusinessAdapter(UIUtils.getContext());
        mPullRefreshListView.setAdapter(nearbyGrouponAdapter);
        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (sort == 0) {
                    //点击商家 TODO
                    String mProductID = nearbyGrouponAdapter.getItem(position - 1).getCouMerID();
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity1.class);
                    intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, mProductID);
                    intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, nearbyGrouponAdapter.getItem(position - 1)
                            .getCouMerImage());
                    showActivity(getActivity(), intent);
                } else {
                    String mCouMerID = nearbyBusinessAdapter.getItem(position - 1).getCouMerID();
                    Bundle bundle = new Bundle();
                    bundle.putString(MerchantDetailActivity.Merchant_ID, mCouMerID);
                    showActivity(getActivity(), MerchantDetailActivity.class, bundle);
                }
            }
        });
    }

    /**
     * 动画 展开 菜单
     */
    private void animDown() {
        float eY = ll_nearby_list_all.getY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_nearby_list_all, "Y", eY, ll_nearby_list_all.getHeight()
                - 1);
        animator.setDuration(100);
        animator.start();
        animator.setInterpolator(AnimationUtils.loadInterpolator(UIUtils.getContext(), android.R
                .interpolator.linear));
    }

    /**
     * 动画 隐藏 菜单
     */
    private void animUp() {
        float eY = ll_nearby_list_all.getY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_nearby_list_all, "Y", eY, 0);
        animator.setDuration(100);
        animator.start();
        animator.setInterpolator(AnimationUtils.loadInterpolator(UIUtils.getContext(), android.R
                .interpolator.linear));
    }


    /**
     * 滚动ListView到指定位置
     *
     * @param pos
     */
    private void setListViewPos(int pos) {
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            mPullRefreshListView.getRefreshableView().smoothScrollToPosition(pos);
        } else {
            mPullRefreshListView.getRefreshableView().setSelection(pos);
        }
    }

    /**
     * 刷新附近按钮状态
     */

    private void refreshLocalButtonName(String name) {
        btn_nearby_list_nearby.setText(name);
        btn_nearby_list_nearby.setTextColor(UIUtils.getContext().getResources().getColor(R.color.color_333333));
        pop.dismiss();
        iv1.setImageResource(R.mipmap.fenlei_jinatou);
    }

    /**
     * 刷新分类商品按钮状态
     */
    private void refreshFoodButtonName(String name) {
        btn_nearby_list_meishi.setText(name);
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        iv2.setImageResource(R.mipmap.fenlei_jinatou);
        btn_nearby_list_meishi.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                .color_333333));
    }

    /**
     * 刷新排序按钮状态
     */
    private void refreshSortButtonName() {
        pop.dismiss();
        iv3.setImageResource(R.mipmap.fenlei_jinatou);
        btn_nearby_list_paixu.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                .color_333333));
    }

    /**
     * 刷新切换商家商品模式初始化按钮显示状态
     */
    private void refreshAllButtonName() {
        btn_nearby_list_nearby.setText(getString(R.string.nearby_fujin));
        btn_nearby_list_meishi.setText(getString(R.string.nearby_meishi));
        btn_nearby_list_paixu.setText(getString(R.string.nearby_paixu));

    }

    private void InitAapter() {
        sort = 0;// 默认显示商品参数
        LocalLeftListAdapter = new NearbyLocalListAdapter(getActivity());
        nearbyLocalRightAdapter = new NearbyLocalRightAdapter(getActivity());
        nearbyFoodListAdapter = new NearbyFoodListAdapter(getActivity());
        nearbyFoodRightAdapter = new NearbyFoodRightAdapter(getActivity());
        nearbyAllAdapter = new NearbyAllLocalAdapter(getActivity());
        nearbySortAdapter = new NearbySortAdapter(getActivity());
        list.add(0, new SortBean(getString(R.string.nearby_xiaoliang), false));
        list.add(1, new SortBean(getString(R.string.nearby_jiage), false));
        list.add(2, new SortBean(getString(R.string.nearby_shangjiashijian), false));
        list.add(3, new SortBean(getString(R.string.nearby_zhekoulu), false));
        list.add(4, new SortBean(getString(R.string.nearby_haopingshu), false));
        Sortlist.add(0, new SortBean(getString(R.string.nearby_pingfen), false));
        Sortlist.add(1, new SortBean(getString(R.string.nearby_renqi), false));
        Sortlist.add(2, new SortBean(getString(R.string.nearby_jiageyou), false));
        Sortlist.add(3, new SortBean(getString(R.string.nearby_huangjing), false));
        Sortlist.add(4, new SortBean(getString(R.string.nearby_fuwu), false));
        checkSortStatus(0);//判断是否商家与商品（默认商品）
        nearbyFilterAdapter = new NearbyFilterAdapter(getActivity());
        filterlist.add(new FilterBean(getString(R.string.nearby_mianyuyue), false, "1"));
        filterlist.add(new FilterBean(getString(R.string.nearby_shangmen), false, "1"));
        filterlist.add(new FilterBean(getString(R.string.nearby_xianshi), false, "1"));
        nearbyFilterAdapter.setGroup(filterlist);
    }

    private void InitonListener() {
        ll_nearby_list_shaixuan.setOnClickListener(this);
        ll_nearby_list_nearby.setOnClickListener(this);
        ll_nearby_list_meishi.setOnClickListener(this);
        ll_nearby_list_paixu.setOnClickListener(this);
        ib_nearby_list_more.setOnClickListener(this);
        tv_left.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        iv_seleteArea.setOnClickListener(this);
        back_to_top.setOnClickListener(this);
        widthPixels = UIUtils.getDisplayMetrics().widthPixels;
        rg_title.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {


            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rb_title_left.getId()) {
                    //团购点击事件
                    sort = 0;
                    ll_nearby_list_shaixuans.setVisibility(View.VISIBLE);
                    ll_nearby_list_more.setVisibility(View.VISIBLE);
                    checkSortStatus(0);//判断是否商家与商品（默认商品）
                    savestatus(sort);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                            (LinearLayout
                                    .LayoutParams.WRAP_CONTENT, LinearLayout
                                    .LayoutParams.MATCH_PARENT);
                    ll_nearby_list_nearby.setLayoutParams(params);
                    ll_nearby_list_meishi.setLayoutParams(params);
                    ll_nearby_list_paixu.setLayoutParams(params);
                    checkStatus(0);
                    dragstatus(sort);
                    changeRefreshModeTwo(totalSizeone);
                    animDown();
                    back_to_top.setVisibility(View.GONE);
                } else {
                    sort = 1;
                    savestatus(sort);
                    checkSortStatus(1);//判断是否商家与商品（默认商品）
                    checkStatus(1);
                    //商家点击事件
                    ll_nearby_list_shaixuans.setVisibility(View.GONE);
                    ll_nearby_list_more.setVisibility(View.GONE);
                    ll_nearby_list_nearby.setMinimumWidth(widthPixels / 3);
                    ll_nearby_list_meishi.setMinimumWidth(widthPixels / 3);
                    ll_nearby_list_paixu.setMinimumWidth(widthPixels / 3);
                    hs_nearby_list_more.setHorizontalScrollBarEnabled(false);
                    dragstatus(sort);
                    changeRefreshModeTwo(totalSizetwo);
                    animDown();
                    back_to_top.setVisibility(View.GONE);
                }
            }
        });
        dragstatus(sort);

    }

    private void dragstatus(int sort) {
        if (sort == 0) {
            hs_nearby_list_more.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        //如果触动屏幕就执行
                        case MotionEvent.ACTION_MOVE:
                            View endView = (View) hs_nearby_list_more.getChildAt(hs_nearby_list_more.getChildCount()
                                    - 1);
                            int endViewRight = endView.getRight();
                            int x = hs_nearby_list_more.getScrollX();
                            if (endViewRight - x - hs_nearby_list_more.getWidth() == 0) {
                                //最右边状态
                                ll_nearby_list_more.setVisibility(View.GONE);
                            } else if (x == 0) {
                                //最左边状态
                                ll_nearby_list_more.setVisibility(View.VISIBLE);
                            } else {
                                ll_nearby_list_more.setVisibility(View.GONE);
                            }

                            break;
                        default:
                            break;

                    }
                    return false;
                }
            });
        } else {
            hs_nearby_list_more.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
        }
    }

    /**
     * 记录点击后的显示状态
     */
    private void savestatus(int status) {
        String proLocalkey = PreferencesHelper.getString("pro_local");
        String proCategory = PreferencesHelper.getString("pro_category");
        String proSortnum = PreferencesHelper.getString("pro_sortnum");
        String merLocalkey = PreferencesHelper.getString("mer_local");
        String merCategory = PreferencesHelper.getString("mer_category");
        String merSortnum = PreferencesHelper.getString("mer_sortnum");
        if (!StringUtils.isEmpty(proCategory) || !StringUtils.isEmpty
                (proSortnum)) {
            if (status == 0) {
                if (!StringUtils.isEmpty(proLocalkey)) {
                    btn_nearby_list_nearby.setText(proLocalkey);
                } else {
                    btn_nearby_list_nearby.setText(getString(R.string.nearby_fujin));
                }
                if (!StringUtils.isEmpty(proCategory)) {
                    btn_nearby_list_meishi.setText(proCategory);
                } else {
                    btn_nearby_list_meishi.setText(getString(R.string.nearby_meishi));
                }
                if (!StringUtils.isEmpty
                        (proSortnum)) {
                    btn_nearby_list_paixu.setText(proSortnum);
                } else {
                    btn_nearby_list_paixu.setText(getString(R.string.nearby_paixu));
                }
            }
        }

        if (status == 1) {
            if (!StringUtils.isEmpty(merLocalkey)) {
                btn_nearby_list_nearby.setText(merLocalkey);
            } else {
                btn_nearby_list_nearby.setText(getString(R.string.nearby_fujin));
            }
            if (!StringUtils.isEmpty(merCategory)) {
                btn_nearby_list_meishi.setText(merCategory);
            } else {
                btn_nearby_list_meishi.setText(getString(R.string.nearby_meishi));
            }
            if (!StringUtils.isEmpty
                    (merSortnum)) {
                btn_nearby_list_paixu.setText(merSortnum);
            } else {
                btn_nearby_list_paixu.setText(getString(R.string.nearby_paixu));
            }
        }
    }


    /**
     * 注册弹出框的布局
     */
    private void assignSeleteViews() {
        final LayoutInflater inflater = LayoutInflater.from(getActivity());
        layouts = inflater.inflate(R.layout.include_house_group_selete, null);
        iv_seleteArea = (View) layouts
                .findViewById(R.id.iv_house_group_select_background);
        lv_seleteArea_left = (ListView) layouts
                .findViewById(R.id.lv_house_group_select_left);
        lv_seleteArea_right = (ListView) layouts
                .findViewById(R.id.lv_house_group_select_right);
        iv_seleteArea.getBackground().setAlpha(153);
    }

    /**
     * @param sort//判断商家与商品
     */
    private void checkSortStatus(int sort) {
        if (sort == 0) {
            nearbySortAdapter.setGroup(list);
            nearbySortAdapter.notifyDataSetChanged();
        } else {
            nearbySortAdapter.setGroup(Sortlist);
            nearbySortAdapter.notifyDataSetChanged();
        }
    }

    /**
     * @param sort//判断商家与商品数据显示列表
     */
    private void checkStatus(int sort) {
        if (sort == 0) {
            hideEmptyLayView();
            if (nearbyGrouponAdapter.getCount() <= 0) {
                showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptytuangou, R.mipmap.emptyseach);
            }
            mPullRefreshListView.setAdapter(nearbyGrouponAdapter);
            nearbyGrouponAdapter.notifyDataSetChanged();
        } else {
            hideEmptyLayView();
            if (nearbyBusinessAdapter.getCount() <= 0) {
                showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptyshangjia, R.mipmap
                        .emptyseach);
            }
            mPullRefreshListView.setAdapter(nearbyBusinessAdapter);
            nearbyBusinessAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);

        lv_seleteArea_left.removeFooterView(getFootView());

        switch (v.getId()) {
            case R.id.lefts://返回

                break;
            case R.id.title_right_ivs://跳入搜索页面
                Bundle bundle = new Bundle();
                bundle.putInt(SearchActivity.SEARCHCHOOSE_ID, sort);
                showActivity(getActivity(), SearchActivity.class, bundle);
                break;
            case R.id.ll_nearby_list_nearby://附近

                if (nearbyAllAdapter != null && nearbyAllAdapter.getCount() > 0) {
                    showLocalALLList();
                } else {
                    executeGetAreas();
                    showLocalALLList();
                }

                break;
            case R.id.ll_nearby_list_meishi://美食
                if (nearbyFoodListAdapter != null && nearbyFoodListAdapter.getCount() > 0) {
                    showLeftFoods();
                } else {
                    executeGetCategories();
                    showLeftFoods();
                }
                break;
            case R.id.ll_nearby_list_paixu://排序

                if (v_seleteArea.getVisibility() == View.VISIBLE) {
                    if (lv_seleteArea_left.getAdapter() instanceof NearbySortAdapter) {
                        pop.dismiss();
                        iv3.setImageResource(R.mipmap.fenlei_jinatou);
                    } else {
                        lv_seleteArea_left.setAdapter(nearbySortAdapter);
                        nearbySortAdapter.notifyDataSetChanged();
                        lv_seleteArea_right.setVisibility(View.GONE);
                    }
                } else {
                    lv_seleteArea_left.setAdapter(nearbySortAdapter);
                    nearbySortAdapter.notifyDataSetChanged();
                    lv_seleteArea_right.setVisibility(View.GONE);
                    openPopWindow(ll_nearby_list_paixu);
                }
                iv3.setImageResource(R.mipmap.fenlei_jinatou2);
                btn_nearby_list_paixu.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_word_yellow));
                break;
            case R.id.ll_nearby_list_shaixuan://筛选
                if (v_seleteArea.getVisibility() == View.VISIBLE) {
                    if (lv_seleteArea_left.getAdapter() instanceof NearbyFilterAdapter) {
                        pop.dismiss();
                        iv4.setImageResource(R.mipmap.fenlei_jinatou);
                    } else {
                        lv_seleteArea_left.addFooterView(getFootView());
                        lv_seleteArea_left.setAdapter(nearbyFilterAdapter);
                        nearbyFilterAdapter.notifyDataSetChanged();
                        lv_seleteArea_right.setVisibility(View.GONE);
                    }
                } else {
                    lv_seleteArea_left.addFooterView(getFootView());
                    lv_seleteArea_left.setAdapter(nearbyFilterAdapter);
                    nearbyFilterAdapter.notifyDataSetChanged();
                    lv_seleteArea_right.setVisibility(View.GONE);
                    openPopWindow(ll_nearby_list_shaixuan);
                }
                iv4.setImageResource(R.mipmap.fenlei_jinatou2);
                btn_nearby_list_shaixuan.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_word_yellow));
                break;
            case R.id.ib_nearby_list_more://分类更多
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        hs_nearby_list_more.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
                    }
                });
                ll_nearby_list_more.setVisibility(View.GONE);
                break;
            case R.id.iv_house_group_select_background://隐藏分类列表
                iv1.setImageResource(R.mipmap.fenlei_jinatou);
                iv2.setImageResource(R.mipmap.fenlei_jinatou);
                iv3.setImageResource(R.mipmap.fenlei_jinatou);
                iv4.setImageResource(R.mipmap.fenlei_jinatou);
                btn_nearby_list_shaixuan.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_333333));
                btn_nearby_list_nearby.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_333333));
                btn_nearby_list_meishi.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_333333));
                btn_nearby_list_paixu.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_333333));
                pop.dismiss();
                break;
            case R.id.btn_submit://隐藏分类列表
                btn_nearby_list_shaixuan.setText(getString(R.string.nearby_shaixuan));
                iv4.setImageResource(R.mipmap.fenlei_jinatou);
                btn_nearby_list_shaixuan.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                        .color_333333));
                int[] content = new int[filterlist.size()];
                FilterBean bean;
                for (int i = 0; i < filterlist.size(); i++) {
                    bean = filterlist.get(i);
                    content[i] = bean.isSelete ? 1 : 0;
                }
                isForOrder = content[0];
                isForHomeDelivery = content[1];
                isForLimitRule = content[2];
                showLoadingDialog("");
                executeGetNearbyGrouponPro();
                pop.dismiss();
                break;
            case R.id.homepage_iv_refresh:
                Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_refresh_rotation);
                LinearInterpolator lir = new LinearInterpolator();
                animation.setInterpolator(lir);
                homepage_iv_refresh.startAnimation(animation);
                gMapUtil.getLatestGeoAddress();
                break;
            case R.id.iv_back_to_top:
                setListViewPos(0);
                animDown();
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(SelectNearByEvent event) {
        if ("NearBy".equals(event.flag)) {
            hideOverLay();
            hideNoNetView();
            hideEmptyLayView();
            animDown();
            setListViewPos(0);
            startOverallLoading(mPullRefreshListView);
            sortnum = 0;
            //初始化团购商品请求网络
            areaId = 0;
            categoryId = 0;
            isForHomeDelivery = 0;
            isForOrder = 0;
            isForLimitRule = 0;
            CURRENT_PAGE = 1;
            CURRENT_PAGES = 1;
            if (sort == 0) {
                executeGetNearbyGrouponPro();
            } else {
                executeGetNearbyGrouponMer();
            }
            releaseSelect();
            PreferencesHelper.setString("pro_local", getString(R.string.nearby_fujin));
            PreferencesHelper.setString("pro_category", getString(R.string.nearby_meishi));
            PreferencesHelper.setString("pro_sortnum", getString(R.string.nearby_paixu));
            PreferencesHelper.setString("mer_local", getString(R.string.nearby_fujin));
            PreferencesHelper.setString("mer_category", getString(R.string.nearby_meishi));
            PreferencesHelper.setString("mer_sortnum", getString(R.string.nearby_paixu));
            btn_nearby_list_shaixuan.setText(getString(R.string.nearby_shaixuan));
            btn_nearby_list_nearby.setText(getString(R.string.nearby_fujin));
            btn_nearby_list_meishi.setText(getString(R.string.nearby_meishi));
            btn_nearby_list_paixu.setText(getString(R.string.nearby_paixu));
        } else {

        }

    }

    private void showLeftFoods() {
        if (v_seleteArea.getVisibility() == View.VISIBLE) {
            if (lv_seleteArea_left.getAdapter() instanceof NearbyFoodListAdapter) {
                pop.dismiss();
                iv2.setImageResource(R.mipmap.fenlei_jinatou);
            } else {
                lv_seleteArea_left.setAdapter(nearbyFoodListAdapter);
                nearbyFoodListAdapter.notifyDataSetChanged();
                lv_seleteArea_right.setVisibility(View.VISIBLE);
                lv_seleteArea_right.setAdapter(nearbyFoodRightAdapter);
                nearbyFoodRightAdapter.notifyDataSetChanged();
            }
        } else {
            lv_seleteArea_left.setAdapter(nearbyFoodListAdapter);
            nearbyFoodListAdapter.notifyDataSetChanged();
            lv_seleteArea_right.setVisibility(View.VISIBLE);
            lv_seleteArea_right.setAdapter(nearbyFoodRightAdapter);
            nearbyFoodRightAdapter.notifyDataSetChanged();
            openPopWindow(ll_nearby_list_meishi);
        }
        iv2.setImageResource(R.mipmap.fenlei_jinatou2);
        btn_nearby_list_meishi.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                .color_word_yellow));
    }

    private void showLocalLeftList() {
        if (v_seleteArea.getVisibility() == View.VISIBLE) {
            if (lv_seleteArea_left.getAdapter() instanceof NearbyLocalListAdapter) {
                pop.dismiss();
                iv1.setImageResource(R.mipmap.fenlei_jinatou);
            } else {
                lv_seleteArea_left.setAdapter(LocalLeftListAdapter);
                LocalLeftListAdapter.notifyDataSetChanged();
                lv_seleteArea_right.setVisibility(View.VISIBLE);
                lv_seleteArea_right.setAdapter(nearbyLocalRightAdapter);
            }
        } else {
            lv_seleteArea_left.setAdapter(LocalLeftListAdapter);
            LocalLeftListAdapter.notifyDataSetChanged();
            lv_seleteArea_right.setVisibility(View.VISIBLE);
            lv_seleteArea_right.setAdapter(nearbyLocalRightAdapter);
            openPopWindow(ll_nearby_list_nearby);
        }
        btn_nearby_list_nearby.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                .color_word_yellow));
        iv1.setImageResource(R.mipmap.fenlei_jinatou2);
    }

    private void showLocalALLList() {
        if (v_seleteArea.getVisibility() == View.VISIBLE) {
            if (lv_seleteArea_left.getAdapter() instanceof NearbyAllLocalAdapter) {
                pop.dismiss();
                iv1.setImageResource(R.mipmap.fenlei_jinatou);
            } else {
                lv_seleteArea_left.setAdapter(nearbyAllAdapter);
                nearbyAllAdapter.notifyDataSetChanged();
                lv_seleteArea_right.setVisibility(View.GONE);
            }
        } else {
            lv_seleteArea_left.setAdapter(nearbyAllAdapter);
            nearbyAllAdapter.notifyDataSetChanged();
            lv_seleteArea_right.setVisibility(View.GONE);
            openPopWindow(ll_nearby_list_nearby);
        }
        btn_nearby_list_nearby.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                .color_word_yellow));
        iv1.setImageResource(R.mipmap.fenlei_jinatou2);
    }

    @Override
    protected void initData() {
        super.initData();
        sort = 0;
        Bundle bundle = getArguments();
        if (bundle != null) {
            sortnumid = bundle.getInt(SORTNUM_ID, -1);
            categoryId = sortnumid;
        }
        PreferencesHelper.setString("pro_local", getString(R.string.nearby_fujin));
        PreferencesHelper.setString("pro_category", getString(R.string.nearby_meishi));
        PreferencesHelper.setString("pro_sortnum", getString(R.string.nearby_paixu));
        PreferencesHelper.setString("mer_local", getString(R.string.nearby_fujin));
        PreferencesHelper.setString("mer_category", getString(R.string.nearby_meishi));
        PreferencesHelper.setString("mer_sortnum", getString(R.string.nearby_paixu));
        CURRENT_PAGE = 1;
        CURRENT_PAGES = 1;
    }

    private View footView;
    private Button btn_submit;

    /**
     * 添加Listview底部视图
     *
     * @return
     */
    private View getFootView() {
        final LayoutInflater inflater = LayoutInflater.from(getActivity());
        if (footView == null) {
            footView = inflater.inflate(R.layout.item_neayby_filterbtn, null);
            btn_submit = (Button) footView
                    .findViewById(R.id.btn_submit);
        }
        btn_submit.setOnClickListener(this);
        return footView;
    }

    public void NET() {


        /*String name = null;
        startOverallLoading(mPullRefreshListView);
        executeGetNearbyGrouponPro();
        for (int i = 0; i < nearbyFoodListAdapter.getCount(); i++) {
            if (categoryId == nearbyFoodListAdapter.getItem(i).CategoryId) {
                name = nearbyFoodListAdapter.getItem(i).CategoryName;
                break;
            }
        }
        if (!StringUtils.isEmpty(name)) {
            btn_nearby_list_meishi.setText(name);
            for (NearbyItemValuesBean bean : nearbyFoodRightAdapter.getGroup()) {
                bean.isSelete = false;
            }
            nearbyFoodRightAdapter.getItem(0).isSelete = true;
            nearbyFoodRightAdapter.notifyDataSetChanged();
            nearbyFoodListAdapter.getItem(mCurrenFoodLeftIndex).ischild = 0;
        }*/
    }

    /**
     * 获取身边(附近)团购
     */
    private void executeGetNearbyGrouponPro() {
        double x = 0;
        double y = 0;
        if (mCurrenSortIndex > 0) {
            if (mCurrenSortIndex >= 2) {
                mCurrenSortIndex = mCurrenSortIndex + 1;
                sortnum = mCurrenSortIndex;
            } else {
                sortnum = mCurrenSortIndex;
            }
        } else {
            sortnum = 0;
        }
        //初始化团购商品请求网络
        if (areaId >= 0) {

        } else {
            areaId = 0;
        }
        if (categoryId >= 0) {
        } else {

            categoryId = 0;
        }
        if (new GMapUtil().getCurrentLat().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLat()) || new
                GMapUtil().getCurrentLng().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLng())) {
            x = 0.000000;
            y = 0.000000;
        } else {
            y = Double.valueOf(new GMapUtil().getCurrentLat());
            x = Double.valueOf(new GMapUtil().getCurrentLng());
        }
        // 刷新
        ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("longitudeX", x);//经度
        ajaxParams.putCommonTypeParam("dimensionsY", y);//维度
        ajaxParams.putCommonTypeParam("nearByAreaId", areaId);//附近地区名称(默认值0，所有地区商品)
        ajaxParams.putCommonTypeParam("categoryId", categoryId);//分类名称(默认值0，所有分类商品)
        ajaxParams.putCommonTypeParam("sort", sortnum);//排序
        ajaxParams.putCommonTypeParam("isForHomeDelivery", isForHomeDelivery);//0、表示所有  1、表示上门
        ajaxParams.putCommonTypeParam("isForOrder", isForOrder);//0、表示所有  1、表示免预约
        ajaxParams.putCommonTypeParam("isForLimitRule", isForLimitRule);//0、表示所有  1、表示不限时
        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        request = new FormResultRequest<List<NearbyGrouponBean>>
                (UrlConstants
                        .NEARBYGROUPON, GetNearbyGrouponPro, this, new
                        TypeToken<RequestResult<List<NearbyGrouponBean>>>() {
                        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private Listener<RequestResult<List<NearbyGrouponBean>>> GetNearbyGrouponPro = new
            Listener<RequestResult<List<NearbyGrouponBean>>>() {
                @Override
                public void onResponse(RequestResult<List<NearbyGrouponBean>> Result) {
                    stopOverallLoading();
                    dismissLoadingDialog();
                    hideEmptyLayView();
                    if (isNoNetView) {
                        hideNoNetView();
                    }
                    checknet = true;
                    if (checknet = true) {
                        mPullRefreshListView.onRefreshComplete();
                    }
                    totalSizeone = Result.getTotalSize();
                    if (Result.flag == 1) {
                        if (Result != null && Result.getRs() != null) {
                            //无数据
                            if (CURRENT_PAGE == 1) {
                                NearbyGrouponList = Result.getRs();
                            } else {
                                NearbyGrouponList.addAll(Result.getRs());
                            }
                            nearbyGrouponAdapter.setGroup(NearbyGrouponList);
                        }
                        if (totalSizeone > 0 && sort == 0) {// 无记录
                            hideEmptyLayView();
                        }
                    } else {
                        showToastMsg(Result.msg);
                    }
                    changeRefreshModeOne(totalSizeone);
                    if (sort == 0 && nearbyGrouponAdapter.getCount() <= 0) {
                        hideEmptyLayView();
                        showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptytuangou, R.mipmap.emptyseach);
                        mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                }
            };

    /**
     * 获取身边(附近)商家
     */
    private void executeGetNearbyGrouponMer() {
        double x = 0;
        double y = 0;
        if (new GMapUtil().getCurrentLat().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLat()) || new
                GMapUtil().getCurrentLng().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLng())) {
            x = 0.000000;
            y = 0.000000;
        } else {
            y = Double.valueOf(new GMapUtil().getCurrentLat());
            x = Double.valueOf(new GMapUtil().getCurrentLng());
        }
        if (mCurrenSortIndex > 0) {
            sortnum = mCurrenSortIndex;
        } else {
            sortnum = 0;
        }
        if (areaId >= 0) {

        } else {
            areaId = 0;
        }
        if (categoryId >= 0) {

        } else {
            categoryId = 0;
        }
        // 刷新
        ajaxParams2 = new JSONWrapAjaxParams();
        ajaxParams2.putCommonTypeParam("pageNo", CURRENT_PAGES);
        ajaxParams2.putCommonTypeParam("longitudeX", x);//经度
        ajaxParams2.putCommonTypeParam("dimensionsY", y);//维度
        ajaxParams2.putCommonTypeParam("nearByAreaId", areaId);//附近地区名称(默认值0，所有地区商品)
        ajaxParams2.putCommonTypeParam("categoryId", categoryId);//分类名称(默认值0，所有分类商品)
        ajaxParams2.putCommonTypeParam("sort", sortnum);//排序
        ajaxParams2.putCommonTypeParam("pageSize", PAGE_SIZE);
        request2 = new FormResultRequest<List<NearbyBusinessBean>>
                (UrlConstants
                        .NEARBYGROUPONMER, GetNearbyGrouponMer, this, new
                        TypeToken<RequestResult<List<NearbyBusinessBean>>>() {
                        }.getType());
        request2.setRequestParams(ajaxParams2);
        executeRequest(request2);
    }

    private Listener<RequestResult<List<NearbyBusinessBean>>> GetNearbyGrouponMer = new
            Listener<RequestResult<List<NearbyBusinessBean>>>() {
                @Override
                public void onResponse(RequestResult<List<NearbyBusinessBean>> Result) {
                    dismissLoadingDialog();
                    stopOverallLoading();
                    if (isNoNetView) {
                        hideNoNetView();
                    }
                    hideEmptyLayView();
                    checknet = true;
                    if (checknet = true) {
                        mPullRefreshListView.onRefreshComplete();
                    }
                    totalSizetwo = Result.getTotalSize();
                    if (Result.flag == 1) {
                        if (Result != null && Result.getRs() != null) {
                            //无数据
                            if (CURRENT_PAGES == 1) {
                                nearbyBusinessList = Result.getRs();
                            } else {
                                nearbyBusinessList.addAll(Result.getRs());
                            }
                            nearbyBusinessAdapter.setGroup(nearbyBusinessList);
                        }
                        if (totalSizetwo > 0 && sort == 1) {// 无记录
                            hideEmptyLayView();
                        }
                    } else {
                        showToastMsg(Result.msg);
                    }
                    changeRefreshModeTwo(totalSizetwo);
                    if (sort == 1 && nearbyBusinessAdapter.getCount() <= 0) {
                        hideEmptyLayView();
                        showEmptyLayView(mPullRefreshListView, R.string.Merchant_emptyshangjia, R.mipmap
                                .emptyseach);
                        mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                }
            };

    @Override
    public void onErrorResponse(VolleyError error) {
        super.onErrorResponse(error);
        stopOverallLoading();
        if (isNoNetView) {
            hideNoNetView();
        }
        if (CURRENT_PAGE == 1 || CURRENT_PAGES == 1 && NetUtil.hasAvailableNet(UIUtils.getContext()
        ) == false) {
            showNoNetView(mPullRefreshListView, reloaClickListener);
        }
        mPullRefreshListView.onRefreshComplete();
    }

    private View.OnClickListener reloaClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // 第一页就加载失败了
            hideOverLay();
            hideNoNetView();
            startOverallLoading(mPullRefreshListView);
            executeGetNearbyGrouponPro();
            executeGetAreas();
            executeGetCategories();
            executeGetNearbyGrouponMer();
        }
    };

    /**
     * 获取附近分类列表
     */
    private void executeGetAreas() {
        FormResultRequest<List<NearbyLocalListBean>> request = new FormResultRequest<List<NearbyLocalListBean>>
                (UrlConstants
                        .GETAREAS, GetAreas, this, new TypeToken<RequestResult<List<NearbyLocalListBean>>>() {
                }.getType());
        executeRequest(request);
    }

    private Listener<RequestResult<List<NearbyLocalListBean>>> GetAreas = new
            Listener<RequestResult<List<NearbyLocalListBean>>>() {
                @Override
                public void onResponse(RequestResult<List<NearbyLocalListBean>> Result) {
                    if (Result.flag == 1) {
                        LocalList = Result.getRs();
                        LocalItemList = LocalList.get(1).nodes;
                        LocalAlllist = LocalItemList.get(1).nodes;
                        nearbyAllAdapter.setGroup(LocalAlllist);
//                        //显示
//                        showLocalLeftList();
                    }
                }
            };

    /**
     * 获取商品分类列表
     */
    private void executeGetCategories() {
        FormResultRequest<List<NearbyListBean>> request = new FormResultRequest<List<NearbyListBean>>
                (UrlConstants
                        .GETCATEGORIES, GetCategories, this, new TypeToken<RequestResult<List<NearbyListBean>>>() {
                }.getType());
        executeRequest(request);
    }

    private Listener<RequestResult<List<NearbyListBean>>> GetCategories = new
            Listener<RequestResult<List<NearbyListBean>>>() {
                @Override
                public void onResponse(RequestResult<List<NearbyListBean>> Result) {
                    if (Result.flag == 1) {
                        GoodsList = Result.getRs();
                    }
                    nearbyFoodListAdapter.setGroup(GoodsList);
                }
            };

    /***
     * 弹出自定义的菜单
     ***/
    public void openPopWindow(View viewselect) {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        if (pop == null) {
            pop = new PopupWindow(layouts, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams
                    .MATCH_PARENT, true);
           /* pop.setAnimationStyle(android.R.style.Animation_InputMethod);*/
         /*   pop.setAnimationStyle(R.style.menu_anima_style);*/
            pop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            // 设置popupwindow可点击
            pop.setTouchable(true);
            // 设置popupwindow外部可点击
            pop.setOutsideTouchable(true);
            // 获取焦点
            pop.setFocusable(true);
            //在这里设置背景才不会出现Selector的问题
            //设置popwindow大小
            pop.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getActivity().getResources(), R
                    .color.common_black)));
            pop.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    iv1.setImageResource(R.mipmap.fenlei_jinatou);
                    iv2.setImageResource(R.mipmap.fenlei_jinatou);
                    iv3.setImageResource(R.mipmap.fenlei_jinatou);
                    iv4.setImageResource(R.mipmap.fenlei_jinatou);
                    btn_nearby_list_shaixuan.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                            .color_333333));
                    btn_nearby_list_nearby.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                            .color_333333));
                    btn_nearby_list_meishi.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                            .color_333333));
                    btn_nearby_list_paixu.setTextColor(UIUtils.getContext().getResources().getColor(R.color
                            .color_333333));
                }
            });
        }
        /* 设置popupwindow的位置 */
        pop.showAsDropDown(view);
        pop.update();
    }

    @Override
    public void onInitShow() {
//        hideOverLay();
//        showLoadingDialog("");
//      startOverallLoading(mPullRefreshListView);
    }

    /**
     * 根据数组数目改变商品列表下拉控件状态
     *
     * @param totalSize
     */
    private void changeRefreshModeOne(int totalSize) {
        if (totalSize == 0) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        } else if (nearbyGrouponAdapter.getCount() >= totalSize && sort == 0) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    /**
     * 根据数组数目改变商家列表下拉控件状态
     *
     * @param totalSize
     */
    private void changeRefreshModeTwo(int totalSize) {
        if (totalSize == 0) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        } else if (nearbyBusinessAdapter.getCount() >= totalSize && sort == 1) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    @Override
    public void getLatestAddress(String latestAddress) {
        homepage_tv_refresh_position.setText(latestAddress);
    }

    @Override
    public void stopRefresh() {
        if (homepage_iv_refresh == null || homepage_iv_refresh.getAnimation() == null) {
            return;
        }
        homepage_iv_refresh.clearAnimation();
    }
}
